package com.xiaozhen.quartz.job;

import com.alibaba.nacos.common.utils.CollectionUtils;
import com.xiaozhen.common.core.constant.Constants;
import com.xiaozhen.common.core.domain.R;
import com.xiaozhen.common.core.domain.device.Device;
import com.xiaozhen.common.core.domain.driver.ParseModbusAttribute;
import com.xiaozhen.common.core.domain.driver.ParseModbusDriver;
import com.xiaozhen.common.core.domain.driver.param.ModbusParam;
import com.xiaozhen.common.core.domain.driver.vo.ModbusDriverVo;
import com.xiaozhen.quartz.config.BaseJob;
import com.xiaozhen.quartz.feign.DeviceService;
import com.xiaozhen.quartz.feign.ModbusService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ArrayUtils;
import org.quartz.JobDetail;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.quartz.JobKey;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;

/**
 * HISTORY
 *
 * @author zhenweisheng
 * @date 2021/11/16 16:42
 * @description:
 */
@Slf4j
public class ModbusReadJob implements BaseJob {

    @Autowired
    private ModbusService modbusService;
    @Autowired
    private DeviceService deviceService;

    /**
     * 执行modbus读取任务
     *
     * @param context
     * @throws JobExecutionException
     */
    @Override
    public void execute(JobExecutionContext context) throws JobExecutionException {
        JobDetail jobDetail = context.getJobDetail();
        JobKey jobKey = jobDetail.getKey();
        //设备ID
        String deviceId = jobKey.getName();
        log.info("设备ID:{}", deviceId);
        R<ModbusDriverVo> modbusDeviceInfo = deviceService.getModbusDeviceInfo(Long.parseLong(deviceId));
        if (modbusDeviceInfo.getCode() == Constants.SUCCESS) {
            ModbusDriverVo modbusDriver = modbusDeviceInfo.getData();
            List<ParseModbusAttribute> attributeList = modbusDriver.getAttributeList();
            if (CollectionUtils.isNotEmpty(attributeList)) {
                attributeList.forEach(attribute -> {
                    //封装参数
                    ModbusParam modbusParam = new ModbusParam();
                    modbusParam.setDevice(modbusDriver.getDevice());
                    modbusParam.setDriver(modbusDriver.getDriver());
                    modbusParam.setAttribute(attribute);
                    R<String> response = modbusService.read(modbusParam);
                    if (response.getCode() == Constants.SUCCESS) {
                        log.info("读取数据结果：{}", response.getData());
                    } else {
                        log.info("读取数据失败");
                    }
                });
            }
        }
    }
}
